<template>
  <el-card shadow="never" class="app-page only" header="文章管理">
    <transition enter-active-class="animate__animated animate__fadeInUp" leave-active-class="animate__animated animate__fadeOut" :duration="800">
      <div class="app-card-header" v-show="showSearch">
        <el-form ref="formQueryRef" :model="queryForm" :inline="true" @submit.prevent>
          <el-form-item label="栏目" prop="modelData">
            <MyModel :list="state.modelData" v-model="state.modelid" @on-change="onModelChange" />
          </el-form-item>
          <el-form-item label="名称" prop="title">
            <el-input v-model="queryForm.title" clearable :style="{ width: '320px' }" placeholder="请输入名称" @keyup.enter="onSearch" />
          </el-form-item>
          <el-form-item>
            <el-space :size="10">
              <el-button type="primary" :icon="Search" @click="onSearch">查询</el-button>
              <el-button :icon="Refresh" @click="onReset(formQueryRef)">重置</el-button>
            </el-space>
          </el-form-item>
        </el-form>
        <el-divider />
      </div>
    </transition>
    <div class="app-card-body">
      <div class="app-table-action">
        <div class="app-table-btn">
          <el-space :size="10">
            <el-button type="primary" :icon="Plus" @click="onAdd">新增</el-button>
            <el-button type="danger" :icon="Delete" :disabled="delDisabled" @click="handleRemove">删除</el-button>
          </el-space>
        </div>
        <div class="app-table-action-right">
          <table-tool-bar v-model:show-search.sync="showSearch" @query-table="getList" />
        </div>
      </div>
      <!-- /table-action -->
      <div class="app-table-container">
        <el-table :data="state.tableData" border v-loading="tableLoading" stripe row-key="id" ref="multipleTableRef" :row-click="toggleSelection" @selection-change="handleSelectionChange" size="large" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="序号" />
          <el-table-column prop="title" label="标题" width="400">
            <template v-slot="scope">
              <a :href="`/article/${scope.row.id}`" target="_blank" v-html="scope.row.title"></a>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" />
          <el-table-column prop="model" label="栏目" />
          <el-table-column prop="category_title" label="分类" />
          <el-table-column label="类型" width="70" class-name="category-cell">
            <template v-slot="scope">
              <el-tooltip class="item" effect="dark" content="Markdown" placement="top" v-if="scope.row.md">
                <span class="app-artile-fa-type"><i-AntDesignFileMarkdownOutlined class="md" /></span>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="文本" placement="top" v-else>
                <span class="app-artile-fa-type"><i-ep-document class="txt" /></span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="views" label="点击量" />
          <el-table-column prop="create_time" label="创建时间" width="200" />

          <el-table-column label="操作" width="180">
            <template v-slot="scope">
              <el-button type="primary" link :icon="EditIcon" @click="handleEdit(scope.row)">编辑</el-button>
              <el-popconfirm title="您确定删除这行数据吗？" @confirm="onRemove(scope.row.id)">
                <template #reference>
                  <el-button type="danger" link :icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <template v-slot:empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
        <div class="app-table-page">
          <div class="app-table-page-info"></div>
          <el-pagination v-model:current-page="queryForm.page" v-model:page-size="queryForm.limit" background layout="total, prev, pager, next, jumper, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
      <!-- /table-container -->
    </div>
    <Edit :model-form="modelForm" :models="state.models" v-model:edit-visible="editVisible" :set-edit-visible="setEditVisible" :create-data="createData" :update-data="updateData" :dialog-status="dialogStatus" />
  </el-card>
</template>
<script setup lang="ts">
import { TitleMap, BasePagination } from '@/config'
import TableToolBar from '@/components/TableToolBar/index.vue'
import { ElNotification, ElTable, FormInstance } from 'element-plus'
import { Search, Refresh, Plus, Edit as EditIcon, Delete } from '@element-plus/icons-vue'
import { cloneDeep, debounce } from 'lodash'
import { set } from '@vueuse/core'
import Edit from './edit.vue'
import { fetchArticle, fetchCategory } from '@/api'
import { handleCategoryModel } from '@/utils'

interface ModelProps {
  modelData?: any
  category_id?: number
  status?: boolean | number
}

const { page, limit } = BasePagination
const showSearch = ref(true)
const tableLoading = ref(false)
const editVisible = ref(false)
const dialogStatus = ref('create')
const delDisabled = ref(false)
const total = ref(0)
let modelForm = reactive<ModelProps>({})
const queryForm = reactive({ modelid: 0, title: '', page, limit })
const state = reactive<any>({
  tableData: [],
  models: [],
  modelData: [],
})
const formQueryRef = ref<FormInstance>()
const setEditVisible = () => {
  set(editVisible, false)
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<any[]>([])
const toggleSelection = (rows?: any[]) => {
  if (rows) {
    rows.forEach((row) => multipleTableRef.value!.toggleRowSelection(row, false))
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection.map((item: any) => item.id)
}

// 处理切换每页显示数量
const handleSizeChange = (val: any) => {
  if (queryForm.page * val > total.value) {
    queryForm.page = 1
  }
  queryForm.limit = val
  getList()
}

// 处理分页
const handleCurrentChange = (val: number) => {
  if (!val) {
    return
  }

  queryForm.page = val
  getList()
}

const onSearch = debounce(() => {
  getList()
  queryForm.page = 1
}, 500)

const onReset = debounce((formQuery: FormInstance | undefined) => {
  formQuery?.resetFields()
  queryForm.page = 1
  getList()
}, 500)

// 新增
const onAdd = () => {
  modelForm = reactive<ModelProps>({ modelData: state.modelData })
  set(editVisible, true)
  set(dialogStatus, 'create')
}

const onModelChange = (val: any) => {
  queryForm.modelid = val.modelid
  getList()
}

// 获取列表
const getList = () => {
  set(tableLoading, true)

  fetchArticle({ params: queryForm })
    .then((res: any) => {
      Array.isArray(res.rows) && (state.tableData = res?.rows)
      total.value = +res.total
    })
    .finally(() => {
      setTimeout(() => {
        set(tableLoading, false)
      }, 80)
    })
}

getList()

const getCategory = () => {
  set(tableLoading, true)

  fetchCategory().then((res: any) => {
    if (Array.isArray(res.rows)) {
      state.models = res?.rows
      !state.modelData.length && (state.modelData = handleCategoryModel(cloneDeep(res?.rows)))
    }
  })
}

getCategory()

// 编辑
const handleEdit = (row: any) => {
  set(editVisible, true)
  set(dialogStatus, 'update')

  modelForm.modelData = state.modelData
  Object.assign(modelForm, row)
}

const handleRemove = () => {
  onRemove(multipleSelection.value.join(','))
}

// 批量删除
const onRemove = (id: number | string) => {
  fetchArticle({ id, type: 'delete' }).then(() => {
    set(dialogStatus, 'delete')
    refreshData()
  })
}

// 新增数据
const createData = (data: any) => {
  fetchArticle({ params: { ...data }, type: 'post' }).then(() => {
    handleSuccess()
  })
}

// 修改数据
const updateData = (data: any) => {
  fetchArticle({ id: data.id, params: { ...data }, type: 'patch' }).then(() => {
    set(dialogStatus, 'update')
    handleSuccess()
  })
}

// 处理成功
const handleSuccess = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  getList()
  ElNotification({
    type: 'success',
    message: `${TitleMap[dialogStatus.value as keyof typeof TitleMap] || '操作'}成功`,
    duration: 3000,
  })
}

// 监听批量删除按钮
watch(
  () => multipleSelection.value.length,
  (value) => {
    delDisabled.value = !value
  },
  { immediate: true }
)

watch(
  () => queryForm.modelid,
  () => {
    getList()
  }
)
</script>
<style lang="scss">
.app-artile-fa-type {
  .md {
    color: #f60;
  }
  svg {
    color: #aaadad;
  }
}
</style>
